//$URL: http://dasding.googlecode.com/svn/branches/testzeugs/data/dao/mongoDB/src/main/java/de/piratech/dasding/data/database/mongo/UserDataImpl.java $
//$Id: UserDataImpl.java 90 2012-11-20 18:42:49Z amuthmann@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.data.database.mongo;

import com.mongodb.DB;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.data.database.UserData;
import net.vz.mongodb.jackson.DBCursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
public class UserDataImpl extends AbstractMongoDB<User> implements UserData {

  private static final Logger LOG = LoggerFactory.getLogger(UserData.class);

  public UserDataImpl(DB pDB) {
    super(pDB, User.class, COLLECTIONS.USER_COLLECTION);
  }

  @Override
  public User createUser(User pUser) throws DatabaseException {
    LOG.debug("createUser({})", pUser);
    // ensure the user's login is unique 
    if (getUser(pUser.getName()) != null) {
      throw new DatabaseException("Username is not unique");
    }
    return getDBCollection().insert(pUser).getSavedObject();
  }

  @Override
  public void deleteUser(User pUser) {
    LOG.debug("deleteUser({})", pUser);
    getDBCollection().removeById(pUser.getId());
  }

  @Override
  public void updateUser(User pUser) {
    LOG.debug("updateUser({})", pUser);
    getDBCollection().updateById(pUser.getId(), pUser);
  }

  @Override
  public User getUser(String pName) {
    LOG.debug("getUser({})", pName);
    DBCursor<User> cursor = getDBCollection().find().is("name", pName);
    return cursor.hasNext() ? cursor.next() : null;
  }
}
